let avatarFile = null;
const DEFAULT_AVATAR = ""; // 默认头像的base64编码

function previewAvatar(event) {
    const file = event.target.files[0];
    if (file) {
        avatarFile = file;
        const reader = new FileReader();
        const avatarWrapper = document.querySelector('.avatar-wrapper');
        
        // 添加上传中的动画效果
        avatarWrapper.classList.add('uploading');
        
        reader.onload = function(e) {
            const preview = document.getElementById('avatarPreview');
            preview.src = e.target.result;
            
            // 图片加载完成后移除动画效果
            preview.onload = function() {
                setTimeout(() => {
                    avatarWrapper.classList.remove('uploading');
                }, 500);
            }
        }
        reader.readAsDataURL(file);
    }
}

// 点击头像区域触发文件选择
document.querySelector('.avatar-wrapper').addEventListener('click', function() {
    document.getElementById('avatarInput').click();
});

async function handleRegister() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    if (!username || !password || !confirmPassword) {
        alert('请填写完整信息');
        return;
    }

    if (password !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }

    try {
        let headphoto = DEFAULT_AVATAR;
        if (avatarFile) {
            headphoto = await FileUtils.encodeFile(avatarFile);
        }
        
        await API.user.add({
            uid: username,
            password: password,
            headphoto: headphoto,
            utype: 2  // 2 表示普通用户
        });
        
        alert('注册成功');
        window.location.href = 'login.html';
    } catch (error) {
        alert('注册失败：' + error.message);
    }
} 